/*
 * Data Explorer: Visual Elements
 *      visualElements.js
 *
 * last modified: 3/20/11
 * author: James Duran
 *
 * description: Provides the main control file
 *              with functions related to displaying visual
 *              elements. For instance, functions that display
 *              progress/status within the result tab, or functions
 *              that create a graphical chart images or divs.
 *
 * comments: n/a
 */

// setNotifyArea:
//
// appends a notification message to #notifyArea div element
// according to the string parameter.
function setNotifyArea(str) {
    $("<div>").addClass("ui-corner-all ui-state-highlight").text(str).
        appendTo("#notifyArea").fadeOut(4000, function(){$(this).remove();});
}

// getDatasetShortCode:
//
// @param datasetName - string
// returns the short hand code the application uses, given a long hand name of
// a dataset
function getDatasetShortCode(datasetName) {
    var _ds = "empty";
    if(datasetName == "FAA Web Service")
        _ds = "faaws";
    if(datasetName == "USGS Water Quality Web Service")
        _ds = "usgs";
    return _ds;
}

// createDragZoomResult:
//
// @param json - json object
// creates the result text for the dragzoom event, given a properly formatted
// json result object
function createDragZoomResult(json) {
    var _i = 0;
    // resets all map marker nodes, if any previously existed
    unsetMapNodes(nodeArray);
    // clear the results tab
    $("#results").empty();
    // create the result divs
    createResultDiv(false, "Additional Options", "", "resultFilter");
    createResultDiv(false, "Search Results", "", "resultElement01");
    
    // create data filter div for the FAA web service
    if(getDatasetShortCode(ds.name) == "faaws") {
	$("#resultFilterText").append("Filter By: ");

	// upon button click, filter all data based on delays
	$("<button id='delayFilter'>").html("Delays").
	    button({icons: {primary: "ui-icon ui-icon-gear"}}).
	    click(function() {
		    // initialize the result and filter status divs
		    $("#resultElement01Text").empty();
		    $("<div id='filterStatus' style='text-align:center;'>").html("<b>Querying Data Sources...</b>").appendTo("#resultElement01Text");

		    // loop through all the proximity search json results
		    $(json).each(function() {
			    // save the airport name of each json element
			    var _airportName = this.value.name;
			    // make an individual JSONP query
			    JSONQuery("http://services.faa.gov/airport/status/" + this.value.code,
				      function(json_result) {
					  // hide the status when a result has been retreived
					  $("#filterStatus").hide();

					  // display links depending on whether a delay is present or not
					  if(json_result.delay == "true") {
					      $("#resultElement01Text").append("<a href='" + getRootURL() +
									       "?ds=" + getDatasetShortCode(ds.name) +
									       "&q=" + json_result.IATA + "'>" +
									       _airportName + ", " + json_result.IATA +
									       "</a><i style='float:right;'>Active Delay</i><br/>");
					  }
					  if(json_result.delay == "false") {
					      $("#resultElement01Text").append("<a href='" + getRootURL() +
									       "?ds=" + getDatasetShortCode(ds.name) +
									       "&q=" + json_result.IATA + "'>" +
									       _airportName + ", " + json_result.IATA +
									       "</a><i style='float:right;'>No Delay</i><br/>");
					  }
				      }, "?format=json&callback=_jqjsp");
			});
		    $("#filterStatus").show();
		}).appendTo("#resultFilterText");
    }

    // create data filter div for the USGS Web Service
    if(getDatasetShortCode(ds.name) == "usgs") {
	$("#resultFilterText").append("Filter By: ");
	$("<button id='activityFilter'>").html("Activity").
	    button({icons: {primary: "ui-icon ui-icon-gear"}}).
	    click(function() {
		    // initialize the result and filter status divs
		    $("#resultElement01Text").empty();
		    $("<div id='filterStatus' style='text-align:center;'>").html("<b>Querying Data Sources...</b>").appendTo("#resultElement01Text");

		    // loop through all json proximity search data
		    $(json).each(function() {
			    // save the individual site name and code
			    var _siteName = this.value.name;
			    var _siteCode = this.value.code;
			    
			    // make an individual xml query
			    XMLQuery(ADDITIONAL_SOURCES + "?ds=usgs&q=" + _siteCode,
				     function(xml) {
					 // hide the status when a result has been retrieved
					 $("#filterStatus").hide();

					 // count the total number of activities
					 var _x = 0;
					 $(xml).find("Activity").each(function() {
						 _x++;
					     });

					 // if there is no activity for the result
					 if(_x == 0) {
					     $("#resultElement01Text").append("<a href='" + getRootURL() +
									      "?ds=" + getDatasetShortCode(ds.name) +
									      "&q=" + _siteCode + "'>" + _siteName +
									      ", " + _siteCode +
									      "</a><br/><i>No Activity</i><br/><br/>")
					 } else if(_x > 0) {
					     // else if there is at least 1 activity
					     $("#resultElement01Text").append("<a href='" + getRootURL() +
									      "?ds=" + getDatasetShortCode(ds.name) +
									      "&q=" + _siteCode + "'>" + _siteName +
									      ", " + _siteCode +
									      "</a><br/><i>" + _x + " Activities</i><br/><br/>")
					 } else {
					     // else if activity cannot be determined
					     $("#resultElement01Text").append("<a href='" + getRootURL() +
									      "?ds=" + getDatasetShortCode(ds.name) +
									      "&q=" + _siteCode + "'>" + _siteName +
									      ", " + _siteCode +
									      "</a><br/><i>N/A (most likely no activity)</i><br/><br/>")
					 }
				     });
			});
		}).appendTo("#resultFilterText");
	$("#statusFilter").show();
	//$("<button id='Chem1Filter'>").html("Chem 1").
	//    button({icons: {primary: "ui-icon ui-icon-gear"}}).appendTo("#resultFilterText");
    }

    $(json).each(function() {
        var _latlng = new google.maps.LatLng(parseFloat(this.id.latitude),
                                             parseFloat(this.id.longitude));
        // create a new node pointing to _latlng geocode
        // use i + 1 so that the visual interface does not display the 0th element
        var _marker = createNumericalIconMarker(_i + 1);

        nodeArray.push(new google.maps.Marker({icon: _marker, position: _latlng,
                       title: this.value.code + ", " + this.value.name}));
        // set it to the map
        nodeArray[_i].setMap(map);
        var _node = nodeArray[_i];
        google.maps.event.addListener(_node, 'click', function() {
                 // perform a search based on the retrieved marker node
                 if(getDatasetShortCode(ds.name) == "faaws")
                    performFAASearch("dynamic", this);
		 if(getDatasetShortCode(ds.name) == "usgs")
		    USGSWebQuery("dynamic", this);
             });
        // also use i + 1 here to hide the 0th element from the user interface
        $("#resultElement01Text").append((_i + 1) + ". <a href='" + getRootURL() + 
            "?ds=" + getDatasetShortCode(ds.name) + "&q=" + 
            this.value.code + "'>" + this.value.name + ", " + this.value.code + "</a><br/>");
        _i++;
    });
    $("#results").show();
}

// displayFootnotes:
//
// @param attribute - string
// posts a query to retrieve all relevant footnotes for a given data attribute
function displayFootnotes(attribute) {
    $("#footnotes").empty();
    $("#relevancy").empty();
    $.post(FOOTNOTES, {"ds": getDatasetShortCode(ds.name), "attr": attribute}, function(data) {
								$("#relevancy").append(data.length + " Footnotes<hr/>");
                                                                $.each(data, function() {
                                                                    $("#footnotes").append("<b>" + this.created + "</b><br/>");
                                                                    $("#footnotes").append("<p>" + this.footnote + "</p>");});
                                                         }, "json");
}

// showAttributeDialog
//
// display attribute dialog based on string title, body,
// and button array containing string button names and click event handlers
function showAttributeDialog(title, attribute, button) {
    $("#attributeDialog").empty();
    $("#attributeDialog").append("<div id='relevancy'>");
    $("#attributeDialog").append("<div id='footnotes'>");
    $("#attributeDialog").append("<div id='footnoteForm'>");

    $("#footnotes").html("<hr/>");
    $("#footnoteForm").html("<hr/><b>Leave a Footnote:</b><br/>" +
			    "<textarea id='typeFootnote' rows='3' cols='35'></textarea><br/>" +
			    "<button id='submitFootnote' class='ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only' role='button' aria-disabled='false'><span class='ui-button-text'>Submit</span></button>");
    $("#footnoteForm").append("<div id='footnoteStatus'>");

    $("#submitFootnote").click(function(event) {
                                    $.post(FOOTNOTES, { "ds": getDatasetShortCode(ds.name), "attr": attribute, "footnoteBody": $("#typeFootnote").val()});
                                    setTimeout(function() {displayFootnotes(attribute)}, 3000);
				    $("#footnoteForm").fadeOut(1600, "linear");
                               });
    displayFootnotes(attribute);
    $("#attributeDialog").dialog({autoOpen: false,
                              resizable: false,
                              modal: true,
                              buttons: button,
                              "title": title}).dialog("open");
}

// showDataAttributeDialog
//
// display a general attribute dialog that the hover click handler calls
function showDataAttributeDialog(attribute) {
    showAttributeDialog("Footnotes for " + attribute, attribute,
			{"Close": function() {
				$(this).dialog("close");
			    }});
}

// showProgress
//
// @param showStatus - bool
// @param showAnimation - bool
// @param status - string
// displays a string status and/or animation within the result tab depending on
// the parameters given by showStatus and showAnimation
function showProgress(showStatus, showAnimation, status) {
    if(showStatus == true) {
        $("#status").html(status);
        $("#status").show();
    } else {
        $("#status").hide();
    }
    if(showAnimation == true) {
        $("#progressBar").show();
    } else {
        $("#progressBar").hide();
    }
}
//<div id="accordion">
//		<h3><a href="#">An Empty Dataset</a></h3>
//		<div><p>This is dataset 1.</p></div>
//		<h3><a href="#">FAA Web Service</a></h3>
//		<div><p>The FAA Web Service is a web service that allows end-users to  query the current known delays in the National Airspace system as well as the current weather from NOAA by airport code.</p></div>
//                <h3><a href="#">USGS Water Quality Web Service</a></h3>
//                <div><p>The US Geological Survey (USGS) publishes water quality information for thousands of sites across the United States. This dataset allows you to search and view water quality data.</p></div>
//	      </div>
function createAccordionDiv(resultContent, length) {
    $("#results").append("<div id='resultAccordion'>");
    for(var i = 0; i < length; i++) {
        $("#resultAccordion").append("<h3><a href='#'>" + resultContent[i].result_title  + "</a></h3><div>" + resultContent[i].result_content + "</div");
    }
    $("#resultAccordion").accordion({autoHeight: false});
}

// createResultDiv
//
// @param showAlert - bool
// @param title - string
// @param html - string
// create a styled div element within the result tab with a string title
// and html with/without an alert sign specified by showAlert
function createResultDiv(showAlert, title, html, id) {
    if(id != null) {
        $("<div>").attr({id: id, "class": "result-div ui-widget-content ui-corner-all"}).appendTo("#results");
        $("<h3>").attr({"class": "result-header ui-widget-header ui-corner-all"}).html(title).appendTo("#" + id);
        $("<p>").attr({id: id + "Text", style: "padding: 0pt 0.7em;"}).html(html).appendTo("#" + id);
	if(showAlert == true)
            $("<span>").attr({id: id + "AlertIcon", "class": "ui-icon ui-icon-alert", style: "float: left; margin-right: 0.3em;"}).prependTo("#" + id + "Text");
        $("<br>").appendTo("#results");
    }
}

// createDialMeter
//
// create a dial meter image using the google charts api
function createDialMeter(title, width, height, minLabel, medLabel, maxLabel,
                         arrowPosition, arrowLabel, elementID) {
    $("<img>").attr({src: "http://chart.apis.google.com/chart?" +
           "chs=" + width + "x" + height +"&cht=gom&chtt=" + title +"&chd=t:" +
           arrowPosition + "&chxt=x,y&chxl=0:|" + arrowLabel +
           "|1:|" + minLabel + "|" + medLabel + "|" + maxLabel +
	   "&chf=bg,s,00000000"}).appendTo("#" + elementID);
}

// createDelaySummaryPieChart:
//
// create a pie chart image based around the delay summary data provided by
// flyontime.us and attach it to a corresponding element id
function createDelaySummaryPieChart(airportCode, total, onTime, shortDelay, longDelay, canceled, elementID) {
    $("<img>").attr({style: "margin-top: 12em;", src: "http://chart.apis.google.com/chart?cht=p&" +
            "chd=t:" + onTime + "," + shortDelay + "," + longDelay + "," + canceled +
            "&chs=600x300&chtt=Flight+Delay+Summary+for+" + airportCode +
            "+(Based+on+" + total + "+Flights)&chco=3366CC|DC3912|FF9900|109618" +
            "&chl=On%20Time|Short%20Delay%20%3C20%20Min.|Long%20Delay%20%3E20%20Min." +
            "|Canceled/Diverted&chdl=" + onTime + "%|" + shortDelay + "%|" +
            longDelay + "%|" + canceled + "%&chf=bg,s,00000000"}).appendTo("#" + elementID);
}

// createDelayByHourBarChart:
//
// creates a bar chart
function createDelayByHourBarChart(airportCode, onTime, shortDelay, longDelay, cancelled, hour, elementID) {
    var _onTimeStr = arrayToString(",", onTime, false);
    var _shortDelayStr = arrayToString(",", shortDelay, false);
    var _longDelayStr = arrayToString(",", longDelay, false);
    var _cancelledStr = arrayToString(",", cancelled, false);
    var _hourStr = arrayToString("|", hour, true);

    $("<img>").attr({style: "margin-left: 8em;", src: "http://chart.apis.google.com/chart?cht=bhs&" +
		"chco=3366CC,DC3912,FF9900,109618&chs=500x550&chtt=Percentage+of+Flight+Delays+by+Hour+for+" + airportCode +
		"&chd=t:" + _onTimeStr + "|" + _shortDelayStr  + "|" +
		_longDelayStr + "|" + _cancelledStr +
		"&chxt=y&chxl=0:|" + _hourStr + "&chm=N,000000,0,,12,,c|N,000000,1,,12,,c|" +
		"N,000000,2,,12,,c|N,000000,3,,12,,c&chf=bg,s,00000000" +
		"&chdl=%%20On%20Time|%%20Short%20Delay%20%3C20%20Min.|" +
		"%%20Long%20Delay%20%3E20%20Min.|%%20Cancelled/Div.&chbh=a"}).appendTo("#" + elementID);
}

// createTemperatureMeter
//
// create a temperature meter using the google charts api with both celcius c
// and faren. f temperatures
function createTemperatureMeter(c, f, elementID) {
    $("<img>").attr({src: "http://chart.apis.google.com/chart?" +
           "cht=bhs&chs=150x75&chl=0&chtt=Temperature&chd=" +
           "t:" + c + "|" + (f - c) + "&chco=4d89f9,c6d9fd&chbh=20&chm=" +
           "N**+F,000000,-1,,12|N**+C,000000,0,,12,,c&chf=bg,s,00000000"}).appendTo("#" + elementID);
}

// createVisibilityMeter
//
// calls createDialMeter to create a visibility meter with range 0 to 10
function createVisibilityMeter(arrowLabel, elementID) {
    createDialMeter("Visibility+Rating", 150, 80, 0, 5, 10,
                    arrowLabel * 10, arrowLabel, elementID);
}

// runLinkEffect
//
// toggles the animation that shows/hide the link element
function runLinkEffect() {
    // get effect type from
    var selectedEffect = "blind";

    // most effect types need no options passed by default
    var options = {};
    // some effects have required parameters
    if ( selectedEffect === "scale" ) {
	options = {percent: 0};
    } else if ( selectedEffect === "size" ) {
	options = {to: {width: 200, height: 60}};
    }
    // run the effect
    $( "#linkURL" ).toggle( selectedEffect, options, 500 );
}

// createHomeIconMarker:
//
// create a home icon marker for use within the google map element.
// This icon is specifically used within the proximity search feature.
function createHomeIconMarker() {
    return new google.maps.MarkerImage("http://chart.apis.google.com/chart" +
        "?chst=d_map_pin_icon_withshadow&chld=home|65B94A",
        // This marker is 20 pixels wide by 32 pixels tall.
        new google.maps.Size(40, 37),
        // The origin for this image is 0,0.
        new google.maps.Point(0,0),
        // The anchor for this image is the base of the flagpole at 0,32.
        new google.maps.Point(12, 37));
}

// createNumericalIconMarker:
//
// create a numerical icon marker for use within the google map element.
// This icon is specifically used within the proximity search feature.
function createNumericalIconMarker(number) {
    return new google.maps.MarkerImage("http://chart.apis.google.com/chart" +
        "?chst=d_map_pin_letter_withshadow&chld=" + number + ".|FF776B|000000",
        // This marker is 20 pixels wide by 32 pixels tall.
        new google.maps.Size(40, 37),
        // The origin for this image is 0,0.
        new google.maps.Point(0,0),
        // The anchor for this image is the base of the flagpole at 0,32.
        new google.maps.Point(12, 37));
}

// createLinkElement
//
// creates a link element, attaching it to the specified element id
function createLinkElement(url, elementID) {
    $("<div>").attr({id: "linkElement"}).appendTo("#" + elementID);
    $("<button id='link'>").html("Link this Page").
        button({icons: {primary: "ui-icon ui-icon-link"}}).
        click(function() {runLinkEffect();}).appendTo("#linkElement");
    $("<div>").attr({id: "linkURL"}).appendTo("#linkElement");
    $("<input type='textbox'>").attr({readonly: true, value: url, style: "width: 100%;"}).
        click(function() {selectAllText(jQuery(this));}).appendTo("#linkURL");
    $("#linkURL").hide();
}

// createProximitySearchText:
//
// create the main proximity search form present within the result tab
// for each airport result.
function createProximitySearchText() {
    $("#proximitySearchText").append("<br/>Find nearby sites within: ");
    $("<select id='proximityValues'>").
        append("<option value='25'>25 miles</option>").
        append("<option value='50'>50 miles</option>").
        append("<option value='100'>100 miles</option>").
        appendTo("#proximitySearchText");
    $("<button id='performProximitySearch'>").attr({style: "float: right;"}).html("Search").
        button({icons: {primary: "ui-icon ui-icon-search"}}).
        click(function() {
		if(getDatasetShortCode(ds.name) == "faaws")
		    FAAJSONProximitySearch();
		else
		    USGSJSONProximitySearch();
	    }).appendTo("#proximitySearchText");
}

// createProximitySearchElement:
//
// create the main proximity search div within the result tab, then create
// the actual proximity search form.
function createProximitySearchElement(elementID) {
    $("<div>").attr({id: "proximitySearch"}).appendTo("#" + elementID).
        append("<div style='clear:both;'></div>");
    $("<div id='proximitySearchText'>").appendTo("#proximitySearch");
    createProximitySearchText();
}

// hoverEffectHandler:
//
// highlights a result data attribute upon a mouse hover
function hoverEffectHandler() {
    $(this).toggleClass("hover-border");
}

// hoverlickHandler
//
// provides a click handler for a result data attribute that displays
// and attribute dialog window
function hoverClickHandler() {
    var _attribute = $(this).find("b").html();
    showDataAttributeDialog(_attribute);
}

// createUSGSWebServiceResult:
//
// uses createResultDiv to create a customized result panel within the result
// tab for the USGS Water Quality Web Service
function createUSGSWebServiceResult(result, latitude, longitude, code, title, huc) {
    // unless there is a need to dynamically create accordion elements, you do not need this
    //var _accordionContent = [{}];
    var _xi = 0, _a = "";

    // detect if the name field from the usgs web service result is empty
    //if(result.name == "") _a = title;
    //else _a = result.name;

    // clear the results tab
    $("#results").empty();
    // create the result divs
    createResultDiv(false, title, "", "resultElement01");

    // count the total number of activities
    $(result).find("Activity").each(function() {
	    _xi++;
	});

    // if the the USGS Water Quality Web Service returns an empty result, fallback to what the database has
    if(_xi == 0) {
	createResultDiv(true, "Results", "", "resultElement02");
	$("#resultElement01Text").append("<div class='result' style='text-align: center;'><b>" + title + "</b></div>" +
				     "<div class='result'><b>Address:</b> " + formattedAddress + "</div></br>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>USGS Site ID:</b> " + code + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Latitude:</b> " + latitude + "</div>" +
				     "<div style='clear: both;'></div>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>HUC ID:</b> " + huc + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Longitude:</b> " + longitude + "</div>" +
				     "<div style='clear: both;'></div><br/><p style='text-align: center;'>Showing the first of " + _xi + " activities.</p>");
	$("#resultElement02Text").append("The USGS Water Quality Web Service has no information on this site.");
    } else {
	// populate the div containing general result information
	$("#resultElement01Text").append("<div class='result' style='text-align: center;'><b>" + title + "</b></div>" +
				     "<div class='result'><b>Address:</b> " + formattedAddress + "</div></br>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>USGS Site ID:</b> " + code + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Latitude:</b> " + latitude + "</div>" +
				     "<div style='clear: both;'></div>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>HUC ID:</b> " + huc + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Longitude:</b> " + longitude + "</div>" +
				     "<div style='clear: both;'></div><br/><p style='text-align: center;'>Showing the first of " + _xi + " activities.</p>");
    
	// reset the counter variable
	_xi = 0;

	// create a result div for latest activity results
	createResultDiv(false, "Results of Latest Activity", "", "resultElement02");

	// parse through the xml result and display all result values
	$(result).find("Activity").first().find("Result").each(function() {
		if($(this).find("ResultDetectionConditionText").text() == "Not Detected") {
		} else {
		// because i just realized that dumping all data into
		// separate accordion elements isn't the best way to display data
		//_accordionContent[_xi] = {"result_title": $(this).find("ResultDescription").find("CharacteristicName").text(),
		//			"result_content": "<p>" + $(this).find("ResultDescription").find("ResultMeasure").find("ResultMeasureValue").text() + " " + $(this).find("ResultDescription").find("ResultMeasure").find("MeasureUnitCode").text() + "</p>"};
		    $("#resultElement02Text").append("<div class='result'><b>" +
					     $(this).find("ResultDescription").find("CharacteristicName").text() + ":</b> " +
					     $(this).find("ResultDescription").find("ResultMeasure").find("ResultMeasureValue").text() +
					     " " + $(this).find("ResultDescription").find("ResultMeasure").find("MeasureUnitCode").text() + "<div>");
		    _xi++;
	    }
	});

    // display the result div only if there is anything to show
    //    if(_xi == 0) {
	//	$("#resultElement02").destroy();
	//	createErrorDiv("Whoa, it seems there is no data associated with this site. It possibly may no longer be in use.");
	//    }
    }
    
    createResultDiv(false, "Additional Options", "", "resultElement04");
    createLinkElement(getRootURL() + "?ds=usgs&q=" + ds.code, "resultElement04Text");
    createProximitySearchElement("resultElement04Text");
    
    // add a hover and click effect to all result attribute divs
    $("div.result").hover(hoverEffectHandler);
    $("div.result").click(hoverClickHandler);
}

// createFAAWebServiceResult
//
// uses createResultDiv to create a customized result panel within the result
// tab for the FAA Web Service
function createFAAWebServiceResult(result, latitude, longitude, code, title) {

    var _a = "", _c = result.weather.temp, _d = 0;

    // clear the results tab
    $("#results").empty();

    // if the airport data is incomplete, then fallback to what the database has
    if(result.weather.wind == undefined) {
	createResultDiv(false, title, "", "resultElement01");
	createResultDiv(true, "Delays", "", "resultElement02");
	createResultDiv(false, "Additional Options", "", "resultElement04");
	$("#resultElement01Text").append("<div class='result' style='text-align: center;'><b>" + title + "</b></div>" +
				     "<div class='result'><b>Address:</b> " + formattedAddress + "</div><br/>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>ICAO Code:</b> " + result.ICAO + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Latitude:</b> " + latitude + "</div>" +
				     "<div style='clear: both;'></div>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>IATA Code:</b> " + result.IATA + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Longitude:</b> " + longitude + "</div>" +
				     "<div style='clear: both;'></div>");
	$("#resultElement02Text").append("The FAA Web Service has no information on this airport.");
    } else {
	    var _cArray = _c.split(" ");

	    // detect if the name field from the faa web service result is empty
	    if(result.name == "") _a = title;
	    else _a = result.name;

	    if(_c != "") _d = _cArray[2].split("(");
	    //alert("Creating result element.\nTitle: " + _a + "\nTemp C: " + _d[1] + "\nTemp F: " + _cArray[0]);
	    // create div elements to fill the results tab
	    createResultDiv(false, _a, "", "resultElement01");
	    createResultDiv(true, "Delays", "", "resultElement02");
	    createResultDiv(false, "Weather", "", "resultElement03");
	    createResultDiv(false, "Additional Options", "", "resultElement04");

	    // populate the div element containing general airport information
	    $("#resultElement01Text").append("<div class='result' style='text-align: center;'><b>" + _a + "</b></div>" +
				     "<div class='result'><b>Address:</b> " + formattedAddress + "</div><br/>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>ICAO Code:</b> " + result.ICAO + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Latitude:</b> " + latitude + "</div>" +
				     "<div style='clear: both;'></div>" +
				     "<div class='result' style='margin-left: 0em; float: left;'><b>IATA Code:</b> " + result.IATA + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Longitude:</b> " + longitude + "</div>" +
				     "<div style='clear: both;'></div>");

	    // populate the div element containing delay information
	    if(result.delay == "false")
		$("#resultElement02Text").append(result.status.reason);
	    else {
		$("#resultElement02AlertIcon").hide();
		var _delayLength = result.status.minDelay + " - " + result.status.maxDelay;
		var _delayExpiration = result.status.endTime;
		if(result.status.minDelay == "" && result.status.maxDelay == "")
		    _delayLength = "Not Available";
		if(_delayExpiration == "")
		    _delayExpiration = "Not Available";
		$("#resultElement02Text").append("<div class='result' style='margin-left: 0em; float: left;'><b>Type:</b> " + result.status.type + " Delay</div>" +
					 "<div class='result' style='margin-right: 0em; float: right'><b>Length:</b>" + _delayLength + "</div>" +
					 "<div style='clear: both;'></div><br/><div class='result' style='margin-left: 0em; float: left;'><b>Expires:</b> " + _delayExpiration + "</div><br/>" +
					 "<div class='result' style='margin-left: 0em; float: left;'><b>Reason:</b> " + result.status.reason + "</div><br/>");
	    }

	    // populate the div element containing weather information
	    $("#resultElement03Text").append("<div class='result' style='margin-left: 0em; float: left;'><b>Weather:</b> " + result.weather.weather + "</div>" +
				     "<div class='result' style='margin-right: 0em; float: right;'><b>Winds:</b> " + result.weather.wind + "</div>" +
				     "<div style='clear: both'></div><br/>");
	    createVisibilityMeter(result.weather.visibility, "resultElement03Text");
	    createTemperatureMeter(_d[1], _cArray[0], "resultElement03Text");
    }
    // populate the div element containing additional options
    createLinkElement(getRootURL() + "?ds=faaws&q=" + result.IATA, "resultElement04Text");
    createProximitySearchElement("resultElement04Text");

    // add a hover and click effect to all result attribute divs
    $("div.result").hover(hoverEffectHandler);
    $("div.result").click(hoverClickHandler);
}